//
//  HomeVC.m
//  Ginix
//
//  Created by 冯志强 on 2025/2/14.
//

#import "HomeVC.h"
#import "HomeHeadView.h"
#import "HomeQuickView.h"
#import "HomeComView.h"
#import <JXPagingView/JXPagerView.h>
#import "HomeSleepModel.h"
#import "HomeDietaryAdviceView.h"

@interface HomeVC ()<JXPagerViewDelegate,JXCategoryViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) JXPagerView           *pagingView;
@property (nonatomic, strong) JXCategoryTitleView   * myCategoryView;
@property (nonatomic,strong) UIView                 * topView;
@property (nonatomic,strong) HomeHeadView           * headView;
@property (nonatomic,strong) UIButton               * quickBtn;
@property (nonatomic,strong) UIButton               * allBtn;
@property (nonatomic,strong) HomeQuickView          * quickView;
@property (nonatomic,strong) HomeComView            * comView;
@property (nonatomic,strong) HomeDietaryAdviceView  * advView;
@property (nonatomic,assign) CGFloat                contentOffsetY;
@property (nonatomic,strong) HomeSleepModel         * infoModel;
@property (nonatomic,strong) NSMutableArray         * sleepListArray;
@property (nonatomic,strong) NSMutableArray         * historyDataListArray;
@end

@implementation HomeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatNavBtn];
    [self setSubViewLayout];
    [self requestData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNotification:) name:ObtainHistoricalDataNotification object:nil];
}

-(void)creatNavBtn{
    
    UIButton * leftBtn = [[UIButton alloc]initWithFrame:self.navgationView.backBtn.frame];
    [self.navgationView addSubview:leftBtn];
    [leftBtn setImage:[UIImage imageNamed:@"Home_nav_leftBtn"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH - 64, StatusBar, 44, 44)];
    [self.navgationView addSubview:rightBtn];
    [rightBtn setImage:[UIImage imageNamed:@"Home_nav_rightBtn"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside];
}

-(void)leftBtnAction{
    
    if ([UserInfoModel shareInstance].userModel.isBind == 1) {
        id vc = [[NSClassFromString(@"HomeJoinVC") alloc]init];
        [self.navigationController pushViewController:vc animated: YES];
    }
    else{
        id vc = [[NSClassFromString(@"HomeBindVC") alloc]init];
        [self.navigationController pushViewController:vc animated: YES];
    }
}

-(void)rightBtnAction{
    
    id vc = [[NSClassFromString(@"HomeMessageVC") alloc]init];
    [self.navigationController pushViewController:vc animated:YES];

}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self getBatteryIndex];
}

-(void)requestData{
    
    @WeakObj(self)
    [SPNetworkingIns POST:PORT(@"sleep-center/api/ringSleepData/getSleepData") params:@{} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject, NSInteger code) {
        @StrongObj(self)
        self.infoModel = [HomeSleepModel yy_modelWithDictionary:responseObject[@"data"]];
        [self.headView setInfoModel:self.infoModel];
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
    }];
}

-(void)getNotification:(NSNotification *)notification{
    
    [self getBatteryIndex];
}

-(void)getBatteryIndex{
    
    [[BCLRingManager shared] readBatteryLevelWithCompletion:^(BOOL success, NSInteger battery) {
        if (success) {
            NSString * tr = [NSString stringWithFormat:@"%ld",battery];
            [[NSUserDefaults standardUserDefaults] setObject:tr forKey:@"battery"];
            
            if (UserInfoModel.shareInstance.userModel.isBind == 1) {
                [self getNewHistoryData];
            }else{
                [self getAllHistoryData];
            }
        }
    }];
}

-(void)getAllHistoryData{
    
    [self.headView resumeRotationAnimation];
    [self.historyDataListArray removeAllObjects];
    [[NSNotificationCenter defaultCenter] postNotificationName:UpdateDataNotification object:nil];
    @WeakObj(self)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [BDLog info:@"获取全部数据"];
        [[BCLRingManager shared] readAllHistoryDataWithProgress:^(double progress, RingDataModel *data) {
            
            [BDLog info:[NSString stringWithFormat:@"时间戳：%u", data.timestamp]];
            [BDLog info:[NSString stringWithFormat:@"心率：%ld", (long)data.rate]];
            [BDLog info:[NSString stringWithFormat:@"血氧：%ld", (long)data.O2]];
            [BDLog info:[NSString stringWithFormat:@"HRV：%ld", (long)data.hrv]];
            [BDLog info:[NSString stringWithFormat:@"步数：%d", data.stepsOfTheDay]];
            [BDLog info:[NSString stringWithFormat:@"温度：%.2f", data.temp]];
            
            NSDictionary * parm = @{@"time":[NSString stringWithFormat:@"%u", data.timestamp],@"heartRota":@(data.hrv),@"yaLi":@(data.mentalStress),@"heart":@(data.rate),@"q2":@(data.O2),@"temp":[NSString stringWithFormat:@"%.2f", data.temp]};
            [self.historyDataListArray addObject:parm];
        }
                                                     completion:^(BOOL success) {
            @StrongObj(self)
            if (success) {
                [BDLog info:@"读取所有历史数据完成"];
                [self updateHisData];
            } else {
                [BDLog info:@"读取所有历史数据失败"];
                NSDictionary * info = @{@"state":@(YES)};
                [[NSNotificationCenter defaultCenter] postNotificationName:BatteryLevelNotification object:info];
            }
        }];
    });
}

-(void)getNewHistoryData{
    [self.headView resumeRotationAnimation];
    [self.historyDataListArray removeAllObjects];
    [[NSNotificationCenter defaultCenter] postNotificationName:UpdateDataNotification object:nil];
    @WeakObj(self)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [BDLog info:@"获取未上传的数据"];
        [[BCLRingManager shared] readNewHistoryDataWithProgress:^(double progress, RingDataModel * _Nonnull data) {
            [BDLog info:[NSString stringWithFormat:@"时间戳：%u", data.timestamp]];
            [BDLog info:[NSString stringWithFormat:@"心率：%ld", (long)data.rate]];
            [BDLog info:[NSString stringWithFormat:@"血氧：%ld", (long)data.O2]];
            [BDLog info:[NSString stringWithFormat:@"HRV：%ld", (long)data.hrv]];
            [BDLog info:[NSString stringWithFormat:@"步数：%d", data.stepsOfTheDay]];
            [BDLog info:[NSString stringWithFormat:@"温度：%.2f", data.temp]];
            
            NSDictionary * parm = @{@"time":[NSString stringWithFormat:@"%u", data.timestamp],@"heartRota":@(data.hrv),@"yaLi":@(data.mentalStress),@"heart":@(data.rate),@"q2":@(data.O2),@"temp":[NSString stringWithFormat:@"%.2f", data.temp]};
            [self.historyDataListArray addObject:parm];
            
        } completion:^(BOOL success) {
            @StrongObj(self)
            if (success) {
                [BDLog info:@"读取未上传的历史数据完成"];
                [self updateHisData];
            } else {
                [BDLog info:@"读取未上传的历史数据失败"];
                NSDictionary * info = @{@"state":@(YES)};
                [[NSNotificationCenter defaultCenter] postNotificationName:BatteryLevelNotification object:info];
            }
        }];
    });
}

-(void)updateHisData{
    @WeakObj(self)
    [SPNetworkingIns POST:PORT(@"sleep-center/api/ringSleepData/saveSleepDayIndex") params:@{@"jsonHistoryDataBean":[self.historyDataListArray yy_modelToJSONString]} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject, NSInteger code) {
        @StrongObj(self)
        [self updateSleepData];
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}

-(void)updateSleepData{
    [self.sleepListArray removeAllObjects];
    @WeakObj(self)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        RingSleepModel *sleepData = [[BCLRingManager shared] calculateSleepForDate:[NSDate date]];
        if (sleepData) {
            [BDLog info:[NSString stringWithFormat:@"总睡眠时间：%ld小时%ld分钟",
                         (long)sleepData.allHours, (long)sleepData.allMinutes]];
            [BDLog info:[NSString stringWithFormat:@"深度睡眠：%lld分钟", sleepData.highTime / 60]];
            [BDLog info:[NSString stringWithFormat:@"浅度睡眠：%lld分钟", sleepData.lowTime / 60]];
            [BDLog info:[NSString stringWithFormat:@"眼动时间：%lld分钟", sleepData.ydTime / 60]];
            [BDLog info:[NSString stringWithFormat:@"清醒时间：%lld分钟", sleepData.qxTime / 60]];
            NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:sleepData.startTime];
            NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:sleepData.endTime];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            [BDLog info:[NSString stringWithFormat:@"入睡时间：%@",
                         [formatter stringFromDate:startDate]]];
            [BDLog info:[NSString stringWithFormat:@"清醒时间：%@",
                         [formatter stringFromDate:endDate]]];
            
            [BDLog info:[NSString stringWithFormat:@"睡眠数据记录数：%lu",
                         (unsigned long)sleepData.sleepDataList.count]];
            for (RingDataModel *data in sleepData.sleepDataList) {
                [BDLog info:[NSString stringWithFormat:@"时间戳：%u", data.timestamp]];
                [BDLog info:[NSString stringWithFormat:@"睡眠类型：%ld", (long)data.sleepType]];
                
                NSDictionary * parm = @{@"time":[NSString stringWithFormat:@"%u", data.timestamp],@"sleepType":@(data.sleepType),@"stressIndex":@(data.mentalStress)};
                [self.sleepListArray addObject:parm];
            }
            
            NSDictionary * parm = @{@"allMinutes":@((long)sleepData.allHours * 60 + (long)sleepData.allMinutes),@"highTime":@(sleepData.highTime / 60),@"lowTime":@(sleepData.lowTime / 60),@"ydTime":@(sleepData.ydTime / 60),@"qxTime":@(sleepData.qxTime / 60),@"startTime":@(sleepData.startTime),@"endTime":@(sleepData.endTime),@"jsonHistoryDataBean":[self.sleepListArray yy_modelToJSONString]};
            [SPNetworkingIns POST:PORT(@"sleep-center/api/ringSleepData/saveSleepData") params:parm success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject, NSInteger code) {
                @StrongObj(self)
                NSDictionary * info = @{@"state":@(YES)};
                [[NSNotificationCenter defaultCenter] postNotificationName:BatteryLevelNotification object:info];
                [self.headView pauseRotationAnimation];
                [self requestData];
            } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                
            }];
        } else {
            [BDLog info:@"获取睡眠数据失败"];
        }
    });
}

-(void)quickBtnAction{
    
    if (UserInfoModel.shareInstance.userModel.isOver != 1) {
        FhudShowStr(@"请先补全个人信息")
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            id vc = [[NSClassFromString(@"MeSetInfoVC") alloc]init];
            [[UIViewController findNavigationController] pushViewController:vc animated:YES];
        });
        return;
    }
    id vc = [[NSClassFromString(@"HomeQuickCheckVC") alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
   
}

-(void)allBtnAction{
    
    if (UserInfoModel.shareInstance.userModel.isOver != 1) {
        FhudShowStr(@"请先补全个人信息")
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            id vc = [[NSClassFromString(@"MeSetInfoVC") alloc]init];
            [[UIViewController findNavigationController] pushViewController:vc animated:YES];
        });
        return;
    }
    id vc = [[NSClassFromString(@"HomeAllCheckVC") alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)setSubViewLayout{
    
    _topView = [[UIView alloc]initWithFrame:CGRectMake(0,ISUPDATE ? 450 * FMScaleX : 510 * FMScaleX , WIDTH, ISUPDATE ? 44 * FMScaleX : 100 * FMScaleX)];
    _topView.backgroundColor = UIColor.clearColor;
    [_topView addSubview:self.quickBtn];
    [_topView addSubview:self.allBtn];
    [_topView addSubview:self.myCategoryView];
    _pagingView = [[JXPagerView alloc] initWithDelegate:self];
    _pagingView.backgroundColor = UIColor.clearColor;
    _pagingView.mainTableView.backgroundColor = UIColor.clearColor;
    _pagingView.listContainerView.backgroundColor = UIColor.clearColor;
    _pagingView.listContainerView.listCellBackgroundColor = UIColor.clearColor;
    _pagingView.pinSectionHeaderVerticalOffset = 0;
    _pagingView.mainTableView.bounces = NO;
    [self.view addSubview:self.pagingView];
    
    self.myCategoryView.listContainer = (id<JXCategoryViewListContainer>)self.pagingView.listContainerView;

    self.quickBtn.hidden = ISUPDATE;
    self.allBtn.hidden = ISUPDATE;

}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.pagingView.frame = CGRectMake(0, NavHeight, WIDTH, HEIGHT - NavHeight - kSafeAreaHeight - TabBarHeight - 120 * FMScaleX);
}

- (UIView *)tableHeaderViewInPagerView:(JXPagerView *)pagerView {
    return self.headView;
}

- (NSUInteger)tableHeaderViewHeightInPagerView:(JXPagerView *)pagerView {
    return ISUPDATE ? 450 * FMScaleX : 510 * FMScaleX ;
}

- (NSUInteger)heightForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return ISUPDATE ? 44 * FMScaleX : 100 * FMScaleX;
}

- (UIView *)viewForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return self.topView;
}

- (NSInteger)numberOfListsInPagerView:(JXPagerView *)pagerView {
    return self.myCategoryView.titles.count;
}

- (id<JXPagerViewListViewDelegate>)pagerView:(JXPagerView *)pagerView initListAtIndex:(NSInteger)index {
    
    if (ISUPDATE) {
        return self.advView;
    }else{
        if (index == 0) {
            return self.quickView;
        }else{
            return self.comView;
        }
    }
}

-(HomeHeadView *)headView{
    
    if (!_headView) {
        _headView = [[HomeHeadView alloc]initWithFrame:CGRectMake(0,0, WIDTH, ISUPDATE ? 450 * FMScaleX : 510 * FMScaleX)];
    }
    return _headView;
}

-(UIButton *)quickBtn{
    
    if (!_quickBtn) {
        _quickBtn = [[UIButton alloc]initWithFrame:CGRectMake(20 * FMScaleX, 0, (WIDTH - 50 * FMScaleX) /2 , 60 * FMScaleX)];
        [_quickBtn setBackgroundImage:[UIImage imageNamed:@"Home_info_quick"] forState:UIControlStateNormal];
        [_quickBtn addTarget:self action:@selector(quickBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _quickBtn;
}
-(UIButton *)allBtn{
    
    if (!_allBtn) {
        _allBtn = [[UIButton alloc]initWithFrame:CGRectMake(GETMaxX(self.quickBtn) + 10 * FMScaleX, 0, (WIDTH - 50 * FMScaleX) /2 , 60 * FMScaleX)];
        [_allBtn setBackgroundImage:[UIImage imageNamed:@"Home_info_all"] forState:UIControlStateNormal];
        [_allBtn addTarget:self action:@selector(allBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _allBtn;
}

-(JXCategoryTitleView *)myCategoryView{
    
    if (!_myCategoryView) {
        _myCategoryView = [[JXCategoryTitleView alloc]initWithFrame:CGRectMake(0,ISUPDATE ? 5 * FMScaleX : GETMaxY(self.quickBtn) + 6 * FMScaleX, WIDTH, 34 * FMScaleX)];
        if (ISUPDATE) {
            _myCategoryView.titles = @[@"睡眠状态与建议"];
        }else{
            _myCategoryView.titles = @[@"快速检测报告",@"全面检测报告"];
        }
        _myCategoryView.titleColor = RDRGB(0x666666);
        _myCategoryView.titleSelectedColor = RDRGB(0xAD7D62);
        _myCategoryView.titleLabelZoomEnabled = YES;
        _myCategoryView.titleSelectedFont = Semibold(14);
        _myCategoryView.titleFont = Regular(14);
        
        JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
        lineView.indicatorColor = RDRGB(0xAD7D62);
        lineView.indicatorWidth = 20 * FMScaleX;
        lineView.indicatorHeight = 3;
        _myCategoryView.indicators = @[lineView];
    }
    return _myCategoryView;
}

-(HomeQuickView *)quickView{
    
    if (!_quickView) {
        _quickView = [[HomeQuickView alloc]initWithFrame:CGRectZero];
    }
    return _quickView;
}
-(HomeComView *)comView{
    
    if (!_comView) {
        _comView = [[HomeComView alloc]initWithFrame:CGRectZero];

    }
    return _comView;
}
-(HomeDietaryAdviceView *)advView{
    
    if (!_advView) {
        _advView = [[HomeDietaryAdviceView alloc]initWithFrame:CGRectZero];
    }
    return _advView;
}

-(NSMutableArray *)sleepListArray{
    
    if (!_sleepListArray) {
        _sleepListArray = [[NSMutableArray alloc]init];
    }
    return _sleepListArray;
}
-(NSMutableArray *)historyDataListArray{
    
    if (!_historyDataListArray) {
        _historyDataListArray = [[NSMutableArray alloc]init];
    }
    return _historyDataListArray;
}
@end
